package com.cainiao.controller;

import com.cainiao.bean.Employee;
import com.cainiao.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * @author shkstart
 * @create 2021-08-06 21:35
 */
@Controller
public class EmployeeController {
    @Autowired
    private EmployeeDao employeeDao;

    /**
     * 查询所有员工
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/employee", method = RequestMethod.GET)
    public String getAllEmployee(Model model) {
        Collection<Employee> empList = employeeDao.getAll();
        model.addAttribute("empList", empList);
        return "employee_list";
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE)
    public String deleteOneEmployee(@PathVariable("id") String id) {
        employeeDao.delete(Integer.parseInt(id));
        //需要重定向 员工列表，地址栏需要改变
        return "redirect:/employee";
    }

    /**
     * 添加
     *
     * @param employee
     * @return
     */
    @PostMapping(value = "/employee")
    public String addEmplooyee(Employee employee) {
        employeeDao.save(employee);
        //需要重定向 员工列表，地址栏需要改变
        return "redirect:/employee";
    }

    /**
     * 根据 id查询单个
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/employee/{id}", method = RequestMethod.GET)
    public String updateEmployee(@PathVariable("id") Integer id, Model model) {
        Employee employee = employeeDao.get(id);
        model.addAttribute("employee", employee);
        return "employee_update";
    }

    @RequestMapping(value = "/employee", method = RequestMethod.PUT)
    public String updateEmployee(Employee employee) {
        employeeDao.save(employee);
        //重定向到当前的列表功能
        return "redirect:/employee";
    }
}
